package com.zcl.Thread.t5;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/9  17:05
 * <p>
 * 使用同步方法解决实现Runnable接口的线程安全问题
 */

class Method implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {

        while (true) {
            show();
        }
    }

    private synchronized void show() {
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ": 卖票,票号为: " + ticket);
            ticket--;
        }
    }
}

public class TicketMethod {
    public static void main(String[] args) {

        Method method = new Method();

        Thread thread1 = new Thread(method);
        Thread thread2 = new Thread(method);
        Thread thread3 = new Thread(method);

        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}
